<script>
import { addProductOrders, getAcceptAddressList } from '@/api/mall.js';
import { GetUserCoupons } from '@/api/homePage.js';

export default {
  name: "predetermined",
  data() {
    return {
      cartProducts: [], // 购物车商品列表
      selectedAddress: null, // 选中的收货地址
      showAddressSelector: false, // 是否显示地址选择器
      
      // 优惠券相关
      hasCoupons: false,
      useCoupons: [],
      couponTotalDiscount: 0,
      
      // 价格相关
      productTotalPrice: 0, // 商品总价
      freight: 0, // 运费
      lastTotalPrice: 0, // 上次总价（用于动画）
      
      // 提交状态
      isSubmitting: false,
      
      remark: '' // 订单备注
    }
  },
  computed: {
    // 计算订单总金额
    totalAmount() {
      let total = this.productTotalPrice + this.freight - this.couponTotalDiscount;
      return Math.max(0, total);
    }
  },
  watch: {
    // 监听总价变化
    totalAmount(newVal, oldVal) {
      if (oldVal && newVal !== oldVal) {
        this.lastTotalPrice = parseFloat(oldVal);
      }
    }
  },
  onLoad(options) {
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: this.$t('cart.cartCheckout.title')
    });

    // 解析购物车数据
    if (options.cartData) {
      try {
        this.cartProducts = JSON.parse(decodeURIComponent(options.cartData));
        this.calculateProductTotal();
        console.log('购物车商品数据:', this.cartProducts);
        
        // 获取默认收货地址
        this.getDefaultAddress();
        
        // 获取优惠券信息
        this.getCoupon();
        
      } catch (error) {
        console.error('解析购物车数据失败:', error);
        uni.showToast({
          title: '数据解析失败',
          icon: 'none'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    } else {
      uni.showToast({
        title: '未获取到商品数据',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  
  onShow() {
    // 页面显示时处理返回的数据
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    
    // 处理地址选择返回
    if (currentPage.$vm && currentPage.$vm.selectedAddressData) {
      this.selectedAddress = currentPage.$vm.selectedAddressData;
      currentPage.$vm.selectedAddressData = null; // 清除临时数据
    }
    
    // 处理优惠券选择返回
    if (currentPage.$vm && currentPage.$vm.selectedCouponsData) {
      this.onCouponSelected(currentPage.$vm.selectedCouponsData);
      currentPage.$vm.selectedCouponsData = null; // 清除临时数据
    }
  },
  methods: {
    // 计算商品总价
    calculateProductTotal() {
      this.productTotalPrice = this.cartProducts.reduce((total, item) => {
        const quantity = item.Num || item.Count || 1;
        return total + (item.Price * quantity);
      }, 0);
    },

    // 获取默认收货地址
    async getDefaultAddress() {
      try {
        const { Data } = await getAcceptAddressList({
          Index: 1,
          Size: 100,
        });

        if (Data && Data.length > 0) {
          // 查找默认地址
          const defaultAddress = Data.find(item => item.IsDefault === 1);

          if (defaultAddress) {
            this.selectedAddress = {
              id: defaultAddress.Id,
              name: defaultAddress.Name,
              phone: defaultAddress.Mobile || '',
              province: defaultAddress.Province,
              city: defaultAddress.City,
              county: defaultAddress.County,
              address: defaultAddress.Address,
              isDefault: true
            };
          }
        }
      } catch (error) {
        console.error('获取默认收货地址失败:', error);
      }
    },

    // 获取用户优惠券
    async getCoupon() {
      try {
        // 获取第一个商品的BusinessId（假设购物车中商品来自同一商家）
        const businessId = this.cartProducts[0]?.BusinessId;
        if (!businessId) return;

        const { Data } = await GetUserCoupons({
          Index: 1,
          Size: 100,
          BusinessId: businessId,
          CouponStatus: 1
        });

        if (!Data || !Array.isArray(Data)) {
          this.hasCoupons = false;
          return;
        }

        const currentDate = Date.now();

        // 筛选有效优惠券
        const validCoupons = Data.filter(coupon => {
          const startTime = Date.parse(coupon.EffectStartDatetime);
          const endTime = Date.parse(coupon.EffectEndDatetime);
          return currentDate < endTime && currentDate > startTime;
        });

        this.hasCoupons = validCoupons.length > 0;

      } catch (error) {
        console.error('获取优惠券失败:', error);
        this.hasCoupons = false;
      }
    },

    // 跳转到优惠券选择页面
    navigateToCoupons() {
      const params = {
        businessId: this.cartProducts[0]?.BusinessId,
        totalPrice: this.productTotalPrice,
        productId: this.cartProducts[0]?.ProductId || this.cartProducts[0]?.Id,
        selectedCoupons: this.useCoupons || []
      };

      uni.navigateTo({
        url: '/mall_subpages/goods/coupons?params=' + encodeURIComponent(JSON.stringify(params))
      });
    },

    // 从优惠券页面返回时接收数据
    onCouponSelected(coupons) {
      this.lastTotalPrice = this.totalAmount;
      this.useCoupons = coupons || [];
      this.calculateCouponDiscount();
    },

    // 计算优惠券总折扣金额
    calculateCouponDiscount() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        this.couponTotalDiscount = 0;
        return;
      }

      let totalDiscount = 0;
      this.useCoupons.forEach(coupon => {
        if (coupon.CouponTemple && coupon.CouponTemple.FullReduceAmount) {
          totalDiscount += parseFloat(coupon.CouponTemple.FullReduceAmount);
        }
      });

      this.couponTotalDiscount = Math.min(totalDiscount, this.productTotalPrice);
    },

    // 构建优惠券参数
    buildCouponParams() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        return [];
      }

      return this.useCoupons.map(coupon => ({
        CouponCode: coupon.CouponCode,
        BusinessId: coupon.BusinessIds ? this.cartProducts[0]?.BusinessId : 0
      }));
    },

    // 打开地址选择器
    openAddressSelector() {
      uni.navigateTo({
        url: '/contact_subpages/address/list?type=select'
      });
    },

    // 验证订单数据
    validateOrderData() {
      // 验证收货地址
      if (!this.selectedAddress) {
        uni.showToast({
          title: this.$t('cart.cartCheckout.addressRequired'),
          icon: 'none'
        });
        return false;
      }

      // 验证商品数据
      if (!this.cartProducts || this.cartProducts.length === 0) {
        uni.showToast({
          title: '商品数据不完整',
          icon: 'none'
        });
        return false;
      }

      return true;
    },

    // 构建订单参数
    buildOrderParams() {
      const orderList = this.cartProducts.map(item => {
        const quantity = item.Num || item.Count || 1;
        const productId = item.ProductId || item.Id;
        
        return {
          ProductId: productId,
          ProductName: item.ProductName || item.Name,
          ProductType: item.ProductType || 2, // 线上商品
          Count: quantity,
          PayStatus: 0,
          Point: 0,
          Deposit: 0,
          ContactMobile: this.selectedAddress.phone,
          ContactName: this.selectedAddress.name,
          CouponDiscount: 0,
          OriginalPrice: item.Price,
          PlatformType: 20, // 小程序
          SettleType: 1,
          payType: 0,
          IsTicket: 0,
          ShopId: item.ShopId || 0,
          MerchantId: item.MerchantId || 0,
          OrderRemak: this.remark || '',
          BusinessId: item.BusinessId || 0,
          ProductSpecId: item.ProductSpecId || '',
          Persons: [],
          
          // 收货地址信息
          Address: this.selectedAddress.address,
          City: this.selectedAddress.city,
          County: this.selectedAddress.county,
          Province: this.selectedAddress.province,
          Mobile: this.selectedAddress.phone,
          Name: this.selectedAddress.name,
          AddressId: this.selectedAddress.id
        };
      });

      return {
        OrdersProductList: orderList,
        Coupons: this.buildCouponParams(),
        City: this.selectedAddress.city,
        County: this.selectedAddress.county,
        Mobile: this.selectedAddress.phone,
        Name: this.selectedAddress.name,
        Province: this.selectedAddress.province,
        Address: this.selectedAddress.address
      };
    },

    // 提交订单
    async submitOrder() {
      // 防重复提交
      if (this.isSubmitting) {
        uni.showToast({
          title: this.$t('cart.cartCheckout.submitting'),
          icon: 'none'
        });
        return;
      }

      // 验证订单数据
      if (!this.validateOrderData()) {
        return;
      }

      this.isSubmitting = true;

      // 显示加载提示
      uni.showLoading({
        title: this.$t('cart.cartCheckout.submitting'),
        mask: true
      });

      try {
        // 构建订单参数
        const params = this.buildOrderParams();
        console.log('提交订单参数:', params);

        // 调用创建订单接口
        const { Data } = await addProductOrders(params);

        uni.hideLoading();

        if (!Data || !Data.OrdersOnLineId) {
          uni.showToast({
            title: this.$t('cart.cartCheckout.submitFailed'),
            icon: 'none'
          });
          return;
        }

        // 订单创建成功，跳转到支付页面
        uni.redirectTo({
          url: `/mall_subpages/goods/payment?id=${Data.OrdersOnLineId}&delta=3`
        });

      } catch (error) {
        console.error('提交订单失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: error.Msg || this.$t('cart.cartCheckout.submitFailed'),
          icon: 'none'
        });
      } finally {
        // 延迟重置提交状态，防止快速重复点击
        setTimeout(() => {
          this.isSubmitting = false;
        }, 2000);
      }
    }
  }
}
</script>

<template>
  <view class="cart-checkout-container">
    <!-- 商品信息 -->
    <view class="section-card">
      <view class="section-title">{{$t('cart.cartCheckout.productList')}}</view>
      <view class="product-list">
        <view v-for="(item, index) in cartProducts" :key="index" class="product-item">
          <view class="product-image">
            <image :src="item.Img || item.ProductImg" mode="aspectFill"></image>
          </view>
          <view class="product-info">
            <view class="product-name">{{ item.ProductName || item.Name }}</view>
            <view class="product-spec" v-if="item.ProductSpecStr">{{ item.ProductSpecStr }}</view>
            <view class="product-price-count">
              <text class="price">¥{{ item.Price }}</text>
              <text class="count">×{{ item.Num || item.Count || 1 }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 收货地址 -->
    <view class="section-card">
      <view class="section-title">{{$t('cart.cartCheckout.deliveryAddress')}}</view>
      
      <!-- 已选择的地址 -->
      <view class="selected-address" v-if="selectedAddress" @click="openAddressSelector">
        <view class="address-content">
          <view class="address-header">
            <text class="address-name">{{ selectedAddress.name }}</text>
            <text class="address-phone">{{ selectedAddress.phone }}</text>
          </view>
          <view class="address-detail">
            {{ selectedAddress.province }} {{ selectedAddress.city }} {{ selectedAddress.county }}
            {{ selectedAddress.address }}
          </view>
        </view>
        <view class="address-arrow">
          <image src="/static/home/right-arrow-black.png" class="arrow-icon"></image>
        </view>
      </view>

      <!-- 未选择地址时的提示 -->
      <view class="no-address" v-else @click="openAddressSelector">
        <text class="no-address-tip">{{$t('cart.cartCheckout.selectAddress')}}</text>
        <view class="address-arrow">
          <image src="/static/home/right-arrow-black.png" class="arrow-icon"></image>
        </view>
      </view>
    </view>

    <!-- 优惠券 -->
    <view class="section-card">
      <view class="coupon-section">
        <view class="coupon-header">
          <view class="section-title">{{$t('cart.cartCheckout.couponSection')}}</view>
          <view class="coupon-status" v-if="useCoupons.length > 0">
            已选择{{useCoupons.length}}张优惠券，优惠¥{{couponTotalDiscount.toFixed(2)}}
          </view>
          <view class="coupon-status available" v-else-if="hasCoupons">
            有可用优惠券
          </view>
          <view class="coupon-status unavailable" v-else>
            暂无可用优惠券
          </view>
        </view>
        <view class="coupon-selection" @click="navigateToCoupons">
          <view class="select-text">选择优惠券</view>
          <image src="/static/home/right-arrow-black.png" class="arrow-icon"></image>
        </view>
      </view>
    </view>

    <!-- 订单备注 -->
    <view class="section-card">
      <view class="section-title">订单备注</view>
      <view class="remark-input-wrapper">
        <input 
          class="remark-input" 
          type="text" 
          v-model="remark" 
          placeholder="选填，请输入订单备注"
          placeholder-style="color: #999;"
        />
      </view>
    </view>

    <!-- 价格明细 -->
    <view class="section-card">
      <view class="section-title">{{$t('cart.cartCheckout.orderAmount')}}</view>
      <view class="price-detail">
        <view class="price-row">
          <text class="price-label">{{$t('cart.cartCheckout.productAmount')}}</text>
          <text class="price-value">¥{{ productTotalPrice.toFixed(2) }}</text>
        </view>
        <view class="price-row">
          <text class="price-label">{{$t('cart.cartCheckout.freight')}}</text>
          <text class="price-value">¥{{ freight.toFixed(2) }}</text>
        </view>
        <view class="price-row" v-if="couponTotalDiscount > 0">
          <text class="price-label">{{$t('cart.cartCheckout.discount')}}</text>
          <text class="price-value discount">-¥{{ couponTotalDiscount.toFixed(2) }}</text>
        </view>
        <view class="price-row total-row">
          <text class="price-label">{{$t('cart.cartCheckout.totalAmount')}}</text>
          <text class="price-value total">¥{{ totalAmount.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-bar">
      <view class="bottom-content">
        <view class="total-info">
          <text class="total-label">{{$t('cart.cartCheckout.totalAmount')}}</text>
          <text class="total-price">¥{{ totalAmount.toFixed(2) }}</text>
        </view>
        <view 
          class="submit-btn"
          :class="{ 'disabled': isSubmitting }"
          @click="submitOrder"
        >
          <text>{{ isSubmitting ? $t('cart.cartCheckout.submitting') : $t('cart.cartCheckout.submitOrder') }}</text>
        </view>
      </view>
    </view>


  </view>
</template>

<style scoped lang="scss">
.cart-checkout-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 200rpx;
}

// 通用卡片样式
.section-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

// 商品列表
.product-list {
  .product-item {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx;
      overflow: hidden;
      margin-right: 20rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .product-info {
      flex: 1;

      .product-name {
        font-size: 28rpx;
        color: #333;
        line-height: 1.4;
        margin-bottom: 10rpx;
      }

      .product-spec {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
        background-color: #f8f8f8;
        padding: 6rpx 12rpx;
        border-radius: 4rpx;
        width: fit-content;
      }

      .product-price-count {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price {
          font-size: 28rpx;
          color: #ff4757;
          font-weight: bold;
        }

        .count {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

// 收货地址
.selected-address {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;

  .address-content {
    flex: 1;

    .address-header {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;

      .address-name {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-right: 20rpx;
      }

      .address-phone {
        font-size: 26rpx;
        color: #666;
      }
    }

    .address-detail {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }
  }

  .address-arrow {
    margin-left: 10rpx;

    .arrow-icon {
      width: 24rpx;
      height: 24rpx;
    }
  }
}

.no-address {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 30rpx 20rpx;

  .no-address-tip {
    font-size: 28rpx;
    color: #666;
  }

  .arrow-icon {
    width: 24rpx;
    height: 24rpx;
  }
}

// 优惠券
.coupon-section {
  .coupon-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      margin-bottom: 0;
      margin-right: 20rpx;
      padding-bottom: 0;
      border-bottom: none;
    }

    .coupon-status {
      flex: 1;
      font-size: 24rpx;
      color: #3a7fe6;

      &.available {
        color: #3a7fe6;
      }

      &.unavailable {
        color: #999;
      }
    }
  }

  .coupon-selection {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;

    .select-text {
      font-size: 28rpx;
      color: #666;
    }

    .arrow-icon {
      width: 24rpx;
      height: 24rpx;
    }
  }
}

// 备注输入
.remark-input-wrapper {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;

  .remark-input {
    width: 100%;
    font-size: 28rpx;
    color: #333;
  }
}

// 价格明细
.price-detail {
  .price-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;

    .price-label {
      font-size: 28rpx;
      color: #666;
    }

    .price-value {
      font-size: 28rpx;
      color: #333;

      &.discount {
        color: #ff4757;
      }

      &.total {
        font-size: 32rpx;
        color: #ff4757;
        font-weight: bold;
      }
    }

    &.total-row {
      border-top: 1rpx dashed #f0f0f0;
      padding-top: 20rpx;
      margin-top: 10rpx;

      .price-label {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
      }
    }
  }
}

// 底部提交栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

  .bottom-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .total-info {
      flex: 1;

      .total-label {
        font-size: 24rpx;
        color: #666;
        margin-right: 10rpx;
      }

      .total-price {
        font-size: 36rpx;
        color: #ff4757;
        font-weight: bold;
      }
    }

    .submit-btn {
      background: linear-gradient(135deg, #498fff 0%, #3a7fe6 100%);
      border-radius: 40rpx;
      height: 80rpx;
      padding: 0 50rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      &.disabled {
        opacity: 0.6;
        pointer-events: none;
      }

      text {
        color: #fff;
        font-size: 30rpx;
        font-weight: 500;
      }
    }
  }
}


</style>